package com.lzb.video;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.IOException;

public class MediaPlayerSurfaceActivity extends Activity implements View.OnClickListener{

	/** 视频播放控件*/
	private SurfaceView surfaceView;
	private Display currDisplay;
	/** 给SurfaceView添加CallBack监听 */
    private SurfaceHolder holder; 
    /** 多媒体*/
    private MediaPlayer player; 
    private int vWidth,vHeight; 
    /** 视频路径*/
    private String videoPath = "";
	private Button button;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_surface);

		button = (Button) findViewById(R.id.btn_start);
		button.setOnClickListener(this);
		//获取播放地址
		Intent intent = getIntent();
		videoPath =  intent.getStringExtra("video_Path");
		
		surfaceView = (SurfaceView) findViewById(R.id.surface_surface_view);
		//然后，我们取得当前Display对象
		currDisplay = this.getWindowManager().getDefaultDisplay();
		//下面开始实例化MediaPlayer对象
		player = new MediaPlayer();
		setPlayerListener();
		setHolder();
	}

	/**
	 * 将要播放的视频图像输送到surfaceView
	 */
	private void setHolder() {
		//给SurfaceView添加CallBack监听
		holder = surfaceView.getHolder();
		//为了可以播放视频或者使用Camera预览，我们需要指定其Buffer类型
		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		holder.addCallback(new Callback() {
			/**
			 * Activity进入后台会触发该方法
			 * @param holder
             */
			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				Toast.makeText(MediaPlayerSurfaceActivity.this, "Surface被销毁", Toast.LENGTH_SHORT).show();

			}

			/**
			 *
			 * Activity进入前台会触发该方法
			 *
			 * 当SurfaceView中的Surface被创建的时候被调用*/
			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				Toast.makeText(MediaPlayerSurfaceActivity.this, "Surface被创建", Toast.LENGTH_SHORT).show();
				play();

			}
			/** 当Surface尺寸等参数改变时触发 */
			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {

			}
		});
	}

	/**
	 *
	 * MediaPlayer中的prepare方法和prepareAsync方法的区别
	 * prepare方法是将资源同步缓存到内存中,一般加载本地较小的资源可以用这个,
	 * 如果是较大的资源或者网络资源建议使用prepareAsync方法,异步加载.但如果想让资源启动,即start()起来,
	 * 因为在异步中,如果不设置监听直接start的话,是拿不到这个资源,如果让线程睡眠一段时间,则可以取得资源,因为这个时候,
	 * 异步线程已经取得资源,但不可能使用线程睡眠的方式来获取资源啊.所以就需要设置监听事件setOnPreparedListener();
	 * 来通知MediaPlayer资源已经获取到了,然后实现onPrepared(MediaPlayer mp)方法.在里面启动MediaPlayer
	 * 参考：http://blog.csdn.net/qq_24223073/article/details/69315856
	 * 设置监听示例{@link #setPlayerListener}
	 * 开始播放视频
	 */
	void play() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			surfaceView.setForeground(null);
		}
		if (TextUtils.isEmpty(videoPath)){
			return;
		}
		player.reset();
		//将要播放的视频图像输送到surfaceView
		player.setDisplay(holder);
		try {
			player.setDataSource(videoPath);
//			player.prepare();
			player.prepareAsync();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//首先取得video的宽和高
		vWidth = player.getVideoWidth();
		vHeight = player.getVideoHeight();
		if(vWidth > currDisplay.getWidth() || vHeight > currDisplay.getHeight()){
			//如果video的宽或者高超出了当前屏幕的大小，则要进行缩放
			float wRatio = (float)vWidth/(float)currDisplay.getWidth();
			float hRatio = (float)vHeight/(float)currDisplay.getHeight();
			//选择大的一个进行缩放
			float ratio = Math.max(wRatio, hRatio);
			vWidth = (int)Math.ceil((float)vWidth/ratio);
			vHeight = (int)Math.ceil((float)vHeight/ratio);
			//设置surfaceView的布局参数
			surfaceView.setLayoutParams(new LinearLayout.LayoutParams(vWidth, vHeight - 100));
			//然后开始播放视频
//			player.start();
		}
//		player.start();

	}

	/**
	 * 
	 * 设置播放监听
	 * 
	 * @version 1.0
	 * @createTime 2016-1-20,下午3:04:38
	 * @updateTime 2016-1-20,下午3:04:38
	 * @createAuthor lzb
	 * @updateAuthor
	 * @updateInfo (此处输入修改内容,若无修改可不写.)
	 */
	@SuppressLint("NewApi") @SuppressWarnings("deprecation")
	private void setPlayerListener() {
		//设置播放完监听
        player.setOnCompletionListener(new OnCompletionListener() {
        	/** 当MediaPlayer播放完成后触发 */
			@Override
			public void onCompletion(MediaPlayer mp) {
				Toast.makeText(MediaPlayerSurfaceActivity.this, "播放完成", Toast.LENGTH_SHORT).show();
			}
		}); 
        //播放错误监听
        player.setOnErrorListener(new OnErrorListener() {
			@TargetApi(Build.VERSION_CODES.CUPCAKE) @Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				 switch (what) { 
				   //播放器坏了
			        case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
						Toast.makeText(MediaPlayerSurfaceActivity.this, "播放器坏了", Toast.LENGTH_SHORT).show();
						break;
			            //未知错误
			        case MediaPlayer.MEDIA_ERROR_UNKNOWN:
						Toast.makeText(MediaPlayerSurfaceActivity.this, "未知错误", Toast.LENGTH_SHORT).show();
						break;
			        default: 
			            break; 
			        } 
				return false;
			}
		}); 
        //详细监听
        player.setOnInfoListener(new OnInfoListener() {
        	/** 当一些特定信息出现或者警告时触发 */
			@Override
			public boolean onInfo(MediaPlayer mp, int what, int extra) {
		        switch(what){ 
		        case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING: //视频交叉紊乱
					Toast.makeText(MediaPlayerSurfaceActivity.this, "视频交叉紊乱", Toast.LENGTH_SHORT).show();
					break;
		        case MediaPlayer.MEDIA_INFO_METADATA_UPDATE:  //更新
					Toast.makeText(MediaPlayerSurfaceActivity.this, "更新", Toast.LENGTH_SHORT).show();
					break;
		        case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING: //无法解码
					Toast.makeText(MediaPlayerSurfaceActivity.this, "无法解码", Toast.LENGTH_SHORT).show();
					break;
		        case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:  //不能搜索
					Toast.makeText(MediaPlayerSurfaceActivity.this, "不能搜索", Toast.LENGTH_SHORT).show();
					break;
		        } 
				return false;
			}
		});

        //准备监听 如果是使用异步加载的方式必须要设置该监听，在onPrepared方法中调用start()方法
        player.setOnPreparedListener(new OnPreparedListener() {
        	/** 当prepare完成后，该方法触发，在这里我们播放视频*/
			@Override
			public void onPrepared(MediaPlayer mp) {
				player.start();
			}
		}); 
        
        player.setOnSeekCompleteListener(new OnSeekCompleteListener() {
			/** seek操作完成时触发 */
			@Override
			public void onSeekComplete(MediaPlayer mp) {
				
			}
		}); 
        /** 当video大小改变时触发  这个方法在设置player的source后至少触发一次 */
        player.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
			@Override
			public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
				
			}
		});
	}

	/**
	 * 启动其他Activity或者对话框，暂停播放
	 */
	@Override
	protected void onPause() {
		if (player != null){
			if (player.isPlaying()){
				player.stop();
			}
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if (player != null){
			if (player.isPlaying()){
				player.stop();
			}
			player.release();
		}
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		if (player.isPlaying()){
			player.stop();
			player.reset();
			play();
		}else {
			play();
		}
	}
}
